package com.easy.annex.service.impl;

import com.easy.annex.FileModel;
import com.easy.annex.constant.ErrorCode;
import com.easy.annex.repository.FileRepository;
import com.easy.annex.service.IFileService;
import com.easy.annex.util.MD5Util;
import org.bson.types.Binary;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @CLASS_NAME: FileServiceImpl
 * @Date 2021/6/5 18:05
 * @Author lei.ren
 */
@Service
public class FileServiceImpl implements IFileService {

    @Resource
    private FileRepository fileRepository;

    @Override
    public FileModel saveFile(MultipartFile file, HttpServletRequest request) {
        FileModel fileModel = null;
        try{
            fileModel = new FileModel(file.getOriginalFilename(), file.getContentType(), file.getSize(), new Binary(file.getBytes()));
            fileModel.setMd5(MD5Util.getMD5(file.getInputStream()));
            fileModel.setUploadDate(new Date());
            fileModel.setPath(getDomain(request));
            return fileRepository.save(fileModel);
        } catch (IOException | NoSuchAlgorithmException ex) {
            ex.getStackTrace();
            return fileModel;
        }
    }

    private static String getDomain(HttpServletRequest request) {
        StringBuffer url = request.getRequestURL();
        String contextPath = request.getServletContext().getContextPath();
        return url.delete(url.length() - request.getRequestURI().length(), url.length()).append(contextPath).toString();
    }

    @Override
    public void removeFile(String id) {
        fileRepository.deleteById(id);
    }

    @Override
    public Optional<FileModel> getFileById(String id) {
        return fileRepository.findById(id);
    }

    @Override
    public List<FileModel> listFilesByPage(int pageIndex, int pageSize) {
        if (pageIndex < 1) {
            throw new RuntimeException(ErrorCode.REQUEST_PARAM_ERROR);
        }
        pageIndex = pageIndex - 1;
        Sort sort = Sort.by(Sort.Direction.DESC,"uploadDate");
        Pageable pageable = PageRequest.of(pageIndex, pageSize, sort);
        Page<FileModel>  page = fileRepository.findAll(pageable);
        List<FileModel> list = page.getContent();
        return list;
    }
}
